package com.wiringweb.resolution;

import com.wiringweb.servlet.WiringRequestProcessor;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sad
 */
public class JsonResolution implements Resolution {

    private final Object obj;

    public JsonResolution(Object value) {
        this.obj = value;
    }

    @Override
    public void process(HttpServletRequest request, HttpServletResponse response, WiringRequestProcessor requestProcessor, ServletConfig servletConfig) throws IOException {
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        String message;
        if (obj != null) {
            message = requestProcessor.getJsonSerializer().toJson(obj);
        } else {
            message = null;
        }

        byte[] bytes = message.getBytes("UTF8");
        response.setContentLength(bytes.length);
        response.getOutputStream().write(bytes);
    }
}
